﻿module Runner {
    export function poseQuestion(group: Phaser.Group, callback?: Function, width: number = 400, height: number = 100) {
        var question = Runner.askQuestion(4, 5, Runner.equationType.addition);
        question[0] = question[0] + ' = ';

        var correctAnswer: boolean = false;

        var questionWindow = new TextWindow(group.game, 'QuestionWindow', (group.game.width / 2) - width / 2,
            (group.game.height / 2) - height / 2, width, height, { font: '30px verdana', fill: '#cccccc' });
        var text = questionWindow.writeWindowText(question[0]);

        group.game.input.keyboard.addCallbacks(this, null, null, function (character) {
            if (callback === undefined) {
                checkAnswer(character, questionWindow, text, question);
            } else {
                callback.call(group.game, checkAnswer(character, questionWindow, text, question), group);
            }
        });
    }

    export function checkAnswer(character, questionWindow: TextWindow, questionText: Phaser.Text, question: any[]): boolean {
        if (!isNaN(character)) {
            questionText.setText(question[0] + character);
            if (character == parseInt(question[1])) {
                questionText.destroy(true);
                
                questionWindow.game.input.keyboard.onPressCallback = null;
                questionWindow.destroy(true);
                
                return true;
            }
        }
        return false;
    }

    export function onAnswer(answer: boolean, battle: Battle) {
        if (answer) {
            attack(battle.heroSprite, battle.enemies[0], battle); //attack only one enemy at a time
            
            battle.enemies.forEach(function (enemy) {
                attack(enemy, battle.heroSprite, battle);
            });
            
            window.setTimeout(function () {
                if (battle.hasEnemies()) {
                    poseQuestion(battle, onAnswer);
                }
            }, 1000);
        }
    }
}